package com.edu.cmsservice.controller;

import com.alibaba.nacos.client.naming.utils.RandomUtils;
import com.edu.cmsservice.service.MsmService;
import com.edu.common.utils.R;
import com.edu.common.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
@CrossOrigin
@Api("短信服务")
public class MsmApiController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation("短信发送")
    @GetMapping(value = "/send/{phone}")
    public R code (@ApiParam(value = "phone",name = "phone",required = true)
                @PathVariable String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) return R.ok();

        code=RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);

        boolean isSend = msmService.send(phone, "SMS_180051135", param);

        if (!isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("发送短信失败!");
        }

    }
}
